package cn.codeforfun.common;

import cn.codeforfun.material.Material;
import cn.codeforfun.material.MaterialDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

/**
 * Created by Administrator on 2016/12/18 0018.
 */
@Controller
public class IndexController {

    @Value("${root.tmp.path}")
    private String tmpPath;

    @Autowired
    private MaterialDao materialDao;

    @RequestMapping("/")
    public String index() {
        return "index.html";
    }

    @RequestMapping(value = "/download/{id}", method = RequestMethod.GET)
    public void download(@PathVariable Integer id, HttpServletResponse response) {
        Material one = materialDao.findOne(id);
        if (one == null) return;
        FileUtil.download(new File(tmpPath + one.getName()), response);
    }

    @RequestMapping("/upload")
    @ResponseBody
    public Material upload(
            @RequestParam(name = "file") MultipartFile file) throws IOException {
        if (file == null) return null;
        FileUtil.upload(file, tmpPath);
        return new Material();
    }
}
